package code.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.Charset;

/**
 * @author rocky
 */
public class NettyByteBuf02 {
    public static void main(String[] args) {
        // 创建 byteBuf
        ByteBuf buf = Unpooled.copiedBuffer("hello,world", Charset.forName("utf-8"));

        // 使用相关的方法
        if (buf.hasArray()) { // true
            byte[] content = buf.array();
            // 将 content 转成字符串
            System.out.println(new String(content, Charset.forName("utf-8")));

            System.out.println("byteBuf= " + buf);

            System.out.println(buf.arrayOffset()); // 0
            System.out.println(buf.readerIndex());  // 0
            System.out.println(buf.writerIndex()); // 11

            System.out.println(buf.readByte()); // 104

            System.out.println(buf.capacity()); // 36
            int len = buf.readableBytes(); // 可读字节数 11
            System.out.println("len=" + len);

            for (int i = 0; i < len; i++) {
                System.out.println((char)buf.getByte(i)); // h e l l 0
            }
            // 按照顺序读
            System.out.println(buf.getCharSequence(0,4,Charset.forName("utf-8")));
            System.out.println(buf.getCharSequence(4,6,Charset.forName("utf-8")));
        }
    }
}
